package com.wolfsea.defineviewgrouppaper
import android.content.Context
import android.graphics.Rect
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.ViewGroup
import androidx.appcompat.widget.AppCompatButton
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.get
import com.wolfsea.defineviewgrouppaper.databinding.BottomLayoutBinding

/**
 *@desc  底部布局容器
 *@author liuliheng
 *@time 2022/11/21  18:45
 **/
class BottomLayoutView @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null
) : ConstraintLayout(context, attributeSet) {

    private var downX = 0
    private var downY = 0
    private var movedY = 0

    private var maxMovedY = 0

    private val rect = Rect()
    private val mBinding: BottomLayoutBinding

    private var paperContainer: PaperContainer? = null

    var findAnswerCallback: IFindAnswerCallback? = null

    init {
        val view = LayoutInflater.from(context).inflate(R.layout.bottom_layout, this, false)
        mBinding = BottomLayoutBinding.bind(view)
        addView(
            view,
            ConstraintLayout.LayoutParams(
                ConstraintLayout.LayoutParams.MATCH_PARENT,
                ConstraintLayout.LayoutParams.WRAP_CONTENT
            ).apply {
                marginStart = context.resources.getDimension(R.dimen.dp_20).toInt()
                marginEnd = context.resources.getDimension(R.dimen.dp_20).toInt()
                bottomMargin = context.resources.getDimension(R.dimen.dp_20).toInt()
            }
        )

        mBinding.btnAnswer.disEnabled()
        mBinding.btnEndAnswer.disEnabled()

        mBinding.btnAnswer.setOnClickListener {
            mBinding.btnEndAnswer.disEnabled()
            val answerList = paperContainer?.getAnswers()
            findAnswerCallback?.findAnswer(answerList)
        }

        mBinding.btnStartAnswer.setOnClickListener {
            paperContainer?.setEditable(true)
            mBinding.btnEndAnswer.enabled()
        }

        mBinding.btnEndAnswer.setOnClickListener {
            paperContainer?.setEditable(false)

            mBinding.btnStartAnswer.disEnabled()
            mBinding.btnAnswer.enabled()
        }

        mBinding.btnSkipTitleA.setOnClickListener {
            paperContainer?.skipTo(1)
            Log.d(TAG, "btnSkipTitleA.setOnClickListener")
        }

        mBinding.btnSkipTitleB.setOnClickListener {
            paperContainer?.skipTo(2)
            Log.d(TAG, "btnSkipTitleB.setOnClickListener")
        }

    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        setMeasuredDimension(
            MeasureSpec.getSize(widthMeasureSpec) - paddingStart - paddingEnd,
            MeasureSpec.getSize(heightMeasureSpec) - paddingTop - paddingBottom
        )
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
        val view = get(0)
        val layoutParams = view.layoutParams as ConstraintLayout.LayoutParams
        val l = layoutParams.marginStart
        val r = view.measuredWidth + layoutParams.marginEnd
        var viewHeight = 0
        if (view is ViewGroup) {
            val childrenAmount = view.childCount
            for (j in 0.until(childrenAmount)) {
                if (j % 3 == 0) {
                    val children = view[j]
                    val layoutParams = children.layoutParams as ConstraintLayout.LayoutParams
                    viewHeight += layoutParams.topMargin + layoutParams.bottomMargin + children.measuredHeight
                }
            }
        }
        val t = (bottom - top) - (viewHeight + layoutParams.bottomMargin)
        maxMovedY = -t
        val newt = t + movedY
        val b = viewHeight + newt
        view.layout(l, newt, r, b)
        rect.set(l, newt, r, b)
    }

    override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
        when (ev?.action) {
            MotionEvent.ACTION_DOWN -> {
                downY = ev.y.toInt()
            }
            MotionEvent.ACTION_MOVE -> {
                val actionMoveY = ev.y.toInt()
                if (rect.contains(ev.x.toInt(), actionMoveY)) {
                    //在这里返回false才会处理子view点击事件
                    return Math.abs(actionMoveY - downY) >= MIN_SLIDE_DISTANCE
                }
                downY = actionMoveY
            }
            MotionEvent.ACTION_UP -> {}
        }
        return super.onInterceptTouchEvent(ev)
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        performClick()
        when (event?.action) {
            MotionEvent.ACTION_DOWN -> {
                Log.d(TAG, "onTouchEvent->MotionEvent.ACTION_DOWN")
                return if (rect.contains(event.x.toInt(), event.y.toInt())) {
                    downX = event.x.toInt()
                    downY = event.y.toInt()
                    true
                } else {
                    super.onTouchEvent(event)
                }
            }
            MotionEvent.ACTION_MOVE -> {
                val actionMoveX = event.x.toInt()
                val actionMoveY = event.y.toInt()
                Log.d(TAG, "onTouchEvent->MotionEvent.ACTION_MOVE")
                val movedDiffValue = actionMoveY - downY
                if (Math.abs(movedDiffValue) > Math.abs(actionMoveX - downX)) {
                    movedY += movedDiffValue
                    movedY = if (movedDiffValue > 0) {
                        Math.min(movedY, 0)
                    } else {
                        Math.max(movedY, maxMovedY)
                    }
                }
                requestLayout()
                downX = actionMoveX
                downY = actionMoveY
            }
            MotionEvent.ACTION_UP -> {
                Log.d(TAG, "onTouchEvent->MotionEvent.ACTION_UP")
            }
        }
        return super.onTouchEvent(event)
    }

    override fun performClick(): Boolean {
        return super.performClick()
    }

    fun attachPaperContainer(paperContainer: PaperContainer?) {
        this.paperContainer = paperContainer
    }

    private fun AppCompatButton.enabled() {
        this.isEnabled = true
    }

    private fun AppCompatButton.disEnabled() {
        this.isEnabled = false
    }

    interface IFindAnswerCallback {
        fun findAnswer(answers: MutableList<String>?)
    }

    companion object {
        const val TAG = "BottomLayoutView"
        //最小滑动距离
        const val MIN_SLIDE_DISTANCE = 5
    }
}